#!/bin/sh

# === GLOBAL ===
red="\033[1;31m"
green="\033[1;32m"
yellow="\033[1;33m"
blue="\033[1;34m"
magenta="\033[1;35m"
cyan="\033[1;36m"
cr="\033[0m"

DEPS=("mpv" "sed" "curl" "pup" "cut" "rev")
BASE_URL="https://myanimelist.net"

# === FUNCS ===

kill() {
	printf "$red%s$cr\n" "$*"
	exit 1
}

check_dependencies () {
	for dep in "${DEPS[@]}"
	do
		[ ! $(command -v $dep) != '' ] && kill "$dep not found, it is required for propper Termi-chan usage. Exiting..."
	done
}

query_anime() {
	[ ! $1 != '' ] && kill "I need something to search for, baka! u.u\""
	printf "Searching for: $blue%s$cr\n" $*
	anime_titles=$(curl -s "$BASE_URL/anime.php?q=$1&cat=anime" | pup 'a.icon-watch attr{href}')
	[ -z "$anime_titles" ] && kill "No anime titles found"
	select_title "$anime_titles"
}

select_title() {
	anime_titles=$*
	ct=1
	for title in $anime_titles
	do
		printf "$red[%d]$cr - %s\n" $ct "$(echo $title | rev | cut -d/ -s -f2 | rev | sed 's/_/ /g')"
		ct=$((ct+1))
	done

	printf "\nSelect title by index:"
	read choice
	[[ "$choice" =~ ^[0-9]+$ ]] && printf "\n" || kill "Invalid input. Exiting..."
	
	ct=1
	for title in $anime_titles
	do
		if [ $ct -eq $choice ]; then
			selected_anime=$title
			break
		fi
		ct=$((ct+1))
	done

	[ -z "$selected_anime" ] &&  kill "Invalid index. Exiting..."
	printf "You have chosen $red%s$cr\n" "$(echo $selected_anime | rev | cut -d/ -s -f2 | rev | sed 's/_/ /g')"
	query_episodes "$selected_anime"
}

query_episodes() {
	selected_anime=$*
	episodes=$(curl -s "$selected_anime" | pup 'div.js-video-list-content a.video-list attr{href}')
	
	arr_ep=()
	max_episode_index=0
	for episode in $episodes
	do
		partial=$(echo $episode | rev | cut -d\/ -f1 | rev)
		(( $partial > $max_episode_index )) && max_episode_index=$partial
		#arr_ep+=($episode)
	done
	
	#max_episode_index=${#arr_ep[@]}
	[ $max_episode_index -eq 0 ] && kill "No episodes found for this title!Ç__Ç"
	printf "Select episode index from $red%d$cr to $red%d$cr:\n" 1 $max_episode_index 
	read choice

	[[ "$choice" =~ ^[0-9]+$ ]] && printf "\n" || kill "Invalid input. Exiting..."

	query_video "$(echo $selected_anime | sed "s/video/episode\/$choice/1")" 
}

query_video() {
	episode=$*
	printf "Grabbing episode from $red%s$cr\n" $episode
	video=$(curl -s $episode | pup 'div.video-embed.cleafix a.btn-embedded-denied attr{href}' | sed -e 's/%2F/\//g' -e 's/\/redirect?url=//g' | cut -d\& -f1)
	[ ! $video != '' ] && insist "$episode" 
	play_it_senpai "$video"
}

play_it_senpai(){
	printf "Playing episode from $red%s$cr\n" $*
	mpv $*
}

insist() {
	printf "Some extra...$red persuasion$cr is required fufufu~\n"
	episode=$*
	blob=$(curl -s $episode | pup 'iframe attr{src}')
	episode_id=$(echo $blob | cut -d\= -f3 | cut -d\& -f1)
	[[ "$episode_id" =~ ^[0-9]+$ ]] && printf "\n" || kill "Episode id found: $episode_id. Insisting did not work. Aborting..."
	#episode_title=$(curl -s $episode | pup 'h2.fs18 text{}' | cut -d- -f3 | sed -e 's/^[[:space:]]*//' -e 's/\///g' -e 's/[[:punct:]]//g' -e 's/ /-/g' | xargs)
	anime_title=$(curl -s $episode | pup 'div.spaceit_pad:nth-child(8) text{}' | sed -e 's/Synonyms//g' -e 's/English//g' -e 's/^[[:space:]]*//' -e 's/\///g' -e 's/[!:]//g' -e 's/-//g' -e 's/ /-/g' | xargs)
	episode_number=$(echo $episode | cut -d\/ -f8)
	play_it_senpai "https://www.crunchyroll.com/$anime_title/episode-$episode_number-$episode_id"
}

present() {
	 cat << "EOF"
                            _.mm-._
                        ,::::###d88P:._
                      ,::::::###88P:::::-.
                      |:::::L'\Y8P:::::::::.
                      |::::/ "\\   `:::::::::
                      |:::/   |     `:::::::::.  ,.,
                      |:'\\  ,\      \ `::::::::"   `,
                    /"\'  | '__\      "--:::::::|    `
                   ,  | \-""'  |        .:::::::'    ,'
                   '  /\/     -.|      .\::::::&lt;     ;
                   \_` |,'      |      \_\::::: `..,`
                    / /T      '\ "-.     &gt;::::'
                   L  || ^    |\\  /    |'\::'
                    `( |/H    `M "/     / _|'
                      `"'m     Y  "") _.-" /
                       |.Y,     -' '-/,'  /
                       ;`\          /`.  /
                      /.          ,'  ' /'
                     / `  -       ` .--'/
                    /   \          \| /"
                   |     \         /|_'-.
                    \     \       / |  ,'
                    /      `---'" ` |_
                    '     ___|_...--' |
                   |     ,'  ||       |
                   `.   .  \_/|      .'
                        ' ,:::|    ,'
                       | |::::|  ,'    "Galaxy Police Officer Mihoshi"
                       |,|::; |,'         (from "Tenchi Muyou")
                         `-'             ---- Dov Sherman

████████╗███████╗██████╗ ███╗   ███╗██╗       ██████╗██╗  ██╗ █████╗ ███╗   ██╗
╚══██╔══╝██╔════╝██╔══██╗████╗ ████║██║      ██╔════╝██║  ██║██╔══██╗████╗  ██║
   ██║   █████╗  ██████╔╝██╔████╔██║██║█████╗██║     ███████║███████║██╔██╗ ██║
   ██║   ██╔══╝  ██╔══██╗██║╚██╔╝██║██║╚════╝██║     ██╔══██║██╔══██║██║╚██╗██║
   ██║   ███████╗██║  ██║██║ ╚═╝ ██║██║      ╚██████╗██║  ██║██║  ██║██║ ╚████║
   ╚═╝   ╚══════╝╚═╝  ╚═╝╚═╝     ╚═╝╚═╝       ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝
EOF
}

# === INIT ===
trap "printf '$cr'" INT HUP
check_dependencies
present
query_anime "$*"
